<?php
/**
 * CRMLite Client Model
 *
 * @final
 * @package        Crmlite_Model
 * @version        $Id: ClientModel.php 66 2007-09-10 08:13:09Z etng2004 $
 * @copyright      2006-2007 ETE.CN
 * @author         Yi BO  <etng2004@gmail.com>
 * @license        PHP Version 3.0 {@link http://www.php.net/license/3_0.txt}
 */


/**
 * 客户表
 */
class Crmlite_Db_Table_Client extends Crmlite_Db_Table {
    protected $_name = "clients";
    protected $_primary = "id";
    protected $_referenceMap    = array(
        'Staff' => array(
            'columns'           => 'created_by',
            'refTableClass'     => 'Crmlite_Db_Table_Staff',
            'refColumns'        => 'name'
        ),
    );

}

class ClientModel extends Crmlite_Model
{
    /**
     * 是否撞单
     *
     *
     * @param string $company   新客户公司名称
     * @param string $website   新客户网址
     * @param array $where      客户类型之类的筛选条件,指针方式传递，可用于查找客户
     * @param bool $mohu        是否进行模糊匹配
     * @return bool
     */
    public function isOrderConflict($company, $website, &$where, $mohu = false)
    {
        settype($where, 'array');
        $or_where = array();
        if($mohu)
        {
            empty($company)|| $or_where[] = "clients.company LIKE '%{$company}%'";
            empty($website)|| $or_where[] = "clients.website LIKE '%{$website}%'";
        }
        else
        {
            empty($company)|| $or_where[] = "clients.company = '{$company}'";
            empty($website)|| $or_where[] = "clients.website = '{$website}'";
        }

        if($or_where)$where[] = implode(" OR ", $or_where);
        $sql = "SELECT COUNT(1) FROM clients LEFT JOIN staffs ON clients.created_by = staffs.id";
        if($where)$sql .= ' WHERE ' . implode(' AND ', $where);
        return (bool)$this->db->fetchOne($sql);
    }
    /**
     * 插入新的客户记录
     *
     * 检查了撞单事件的发生
     *
     * @param array $record 客户记录
     * @return bool
     */
    public function insert(&$record)
    {
        $where = array("client_type_code='{$record['client_type_code']}'");
        if($this->isOrderConflict($record['company'], $record['website'], $where))
        {
            $this->pushError("Conflict", "撞单了！");
            return false;
        }
        return parent::insert($record);
    }
}